package com.ht.config.minio.service.impl;


import cn.hutool.core.util.StrUtil;
import com.ht.config.minio.MinioConfig;
import com.ht.config.minio.service.MinioService;
import com.ht.util.FileUtil;
import io.minio.*;
import com.ht.util.ssh.SshResponse;
import com.ht.util.ssh.SshUtils;
import io.minio.errors.*;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author hejialun
 * @ClassName MinioServiceImpl
 * @description: TODO（minio文件操作serviceImpl）
 * @Date: 2024/6/5 14:47
 */
@Service
public class MinioServiceImpl implements MinioService {

    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioConfig minioConfig;

    //定义默认桶
    @Value("${minio.bucket}")
    private String bucketName;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        try (InputStream inputStream = file.getInputStream()) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
        }
        return fileName;
    }

    @Override
    public String uploadFile(byte[] bytes, String fileName) throws Exception {
        fileName = System.currentTimeMillis() + "_" + fileName;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(byteArrayInputStream, byteArrayInputStream.available(), -1)
                            .contentType(FileUtil.getFileNameSuffix(fileName))
                            .build()
            );
        }
        return fileName;
    }

    @Override
    public String uploadFile(InputStream inputStream, long objectSize, String fileName) throws Exception {
        fileName = System.currentTimeMillis() + "_" + fileName;
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(inputStream, objectSize, -1)
                        .build()
        );
        return fileName;
    }

    @Override
    public String uploadFileToPath(byte[] bytes, String path) throws Exception {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(path)
                            .stream(byteArrayInputStream, byteArrayInputStream.available(), -1)
                            .contentType(FileUtil.getFileNameSuffix(path))
                            .build()
            );
        }
        return path;
    }

    @Override
    public InputStream downloadFile(String filePath) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filePath)
                        .build()
        );
    }

    @Override
    public void clearFile() throws Exception {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).recursive(true).build());
        for (Result<Item> result : results) {
            Item item = result.get();
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(item.objectName()).build());
        }
    }

    @Override
    public Boolean fileToPdf(String filePath) {
        //待执行命令
        String command = minioConfig.toPdfCommandInit(filePath);
        try {
            //执行命令
            SshResponse response = SshUtils.runCommand(minioConfig.getSshProperties(), command, 15);
            return response.getReturnCode() == 0 && StrUtil.isEmpty(response.getErrOutput());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public String copyFile(String filePath) throws Exception {
        //设置新文件名称
        String fileName = System.currentTimeMillis() + "_" + filePath;
        minioClient.copyObject(
                CopyObjectArgs.builder()
                        .source(CopySource.builder()
                                .bucket(bucketName)
                                .object(filePath)
                                .build())
                        .bucket(bucketName)
                        .object(fileName)
                        .build()
        );
        return fileName;
    }

    @Override
    public void delByFile(String filePath) throws Exception {
        //minio删除文件
        minioClient.removeObject(
                RemoveObjectArgs
                        .builder()
                        .bucket(bucketName)
                        .object(filePath)
                        .build()
        );
    }
}
